package com.lzw.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lzw.pojo.Result;
import com.lzw.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 处理OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 1、获取URL
        String url = request.getRequestURI();
        log.info("请求的URL: {}", url);

        // 2、判断是否是登录请求
        if (url.contains("adminLogin") || url.contains("studentLogin") || url.contains("maintenanceLogin") || url.contains("apartmentLogin")) {
            log.info("登录操作，放行...");
            return true;
        }

        // 3、获取JWT令牌
        String jwt = request.getHeader("Authorization");
        if (!StringUtils.hasLength(jwt) || !jwt.startsWith("Bearer ")) {
            log.info("token为空或格式错误，返回未登录信息");
            return unauthorizedResponse(response);
        }

        // 4、解析JWT令牌
        try {
            String token = jwt.replace("Bearer ", "");
            Claims claims = JwtUtils.parseJWT(token);
            // 提取三个可能的用户ID
            Integer adminId = (Integer) claims.get("admin_id");
            Integer studentId = (Integer) claims.get("student_id");
            Integer workerId = (Integer) claims.get("worker_id");

            // 检查是否存在至少一个有效ID
            if (adminId == null && studentId == null && workerId == null) {
                log.info("JWT解析失败，未找到有效的用户ID");
                return unauthorizedResponse(response);
            }

            // 根据存在的ID记录日志
            if (adminId != null) {
                log.info("令牌验证通过，admin_id: {}", adminId);
            } else if (studentId != null) {
                log.info("令牌验证通过，student_id: {}", studentId);
            } else {
                log.info("令牌验证通过，worker_id: {}", workerId);
            }
        } catch (Exception e) {
            log.info("JWT解析失败: {}", e.getMessage());
            return unauthorizedResponse(response);
        }

        // 5、放行
        return true;
    }

    private boolean unauthorizedResponse(HttpServletResponse response) throws Exception {
        Result error = Result.error("NOT_LOGIN");
        String notLogin = JSONObject.toJSONString(error);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(notLogin);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标资源运行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("渲染图运行");
    }
}
